<?php
namespace app\ausadmin\controller;
use app\ausadmin\controller\Common;
use think\Request;
use think\File;
use think\Db;
use think\Config;
use think\Controller;
use Godok\Org\Adminauth;
use Godok\Org\FileManager;
use Qcloud\cos\Api;

class Avatar extends Common
{
	/**
	 * 编辑头像
	 */
	public function index()
	{
	    if ( Request::instance()->isPost() ) {
	        $file = Request::instance()->file('image');
	        if ( ! $file instanceof File) {
	            return ['code'=>-1000, 'msg'=>lang("非法上传！")];
	        }
	        if ( !$file->validate(['size'=>1000*200,'ext'=>'jpg,png,gif'])->check() ) {
	            return ['code'=>-1010, 'msg'=>lang($file->getError())];
	        }
	        //$info = FileManager::save($file);
	        $info=$file->move(ROOT_PATH . 'public' . DS . 'uploads');
			$file = $info->getSaveName();
			if($file){
                    $cosApi = new Api(config('Qcloud'));
                    $bucket = config('Qcloud.bucket');
                    $src = ROOT_PATH . 'public/uploads/'.$file;
                    $dst = 'admin/avatar/'. $file;
                    $ret = $cosApi->upload($bucket, $src, $dst);
					if($ret['code']==0){
	                    $path = $ret['data']['resource_path'];  //获取资源文件路径（包含了APPID和bucketname）
	                    $len = strlen($bucket);  //计算bucketname长度
	                    $start = strpos($path,$bucket);   //计算bucketname第一次出现的问题
	                    $start +=$len;  
	                    $newpath = substr($path,$start);  //截取路径
	                    unlink($src);  //删除服务器上面的资源文件
	                    $res['code'] = '1';
	                    $res['picture'] = $newpath;  //资源文件路径（需要前面添加上域名地址才可以使用）
	                    $res['url'] = $ret['data']['access_url'];   //资源文件URL
	                   // $data['index_img'] = $res['picture'];
	                    $res=Db::name( Config::get('auth.admin_user') )
		                ->where(['id' => Adminauth::user('id')])
		                ->update(['avatar'=> $res['picture']]);
		                if($res !==false ){
		                	return ['code'=>0, 'msg'=>lang('保存成功！')];
		                }else{
		                	return ['code'=>-1010, 'msg'=>lang('数据更新失败')];
		                }
	                    //return $res;
	                }   
                }
	        /*if ( $info ) {
	            if(
	                Db::name( Config::get('auth.admin_user') )
	                ->where(['id' => Adminauth::user('id')])
	                ->update(['avatar'=> $info[1]])
	            ) {
	                \think\Cookie::set('avatar',$info[1], 3600*24*7);
	                return ['code'=>0, 'msg'=>'保存成功！'];
	            } else {
	                return ['code'=>-1010, 'msg'=>'数据更新失败'];
	            }
	             
	        } else {
	            return ['code'=>-1000, 'msg'=>FileManager::getError()];
	        }*/
	    } else {
	        return $this->fetch('../application/publicview/avatar/index.html');
	    }
       
	}



}

